package com.wanmait.community.interceptor;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.wanmait.community.entity.User;
import com.wanmait.community.service.UserService;
import com.wanmait.community.util.JWTUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
//拦截器检查token的有效性
public class JWTUserInterceptor implements HandlerInterceptor {

    @Resource
    private UserService userService;

    //控制器的功能处理方法handler执行之前执行的代码
    //返回true表示继续执行控制的handler
    //返回false表示不执行控制器的handler，如果前后端不分离一般配合重定向，如果前后端分离，可以输出一些信息，当然可以抛出异常走统一的异常处理
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果是预检请求，直接放行
        if("OPTIONS".equals(request.getMethod())) {
            return true;
        }
        //从请求头中获得token
        String token = request.getHeader("userToken");
        if(token == null) {
            throw new JWTVerificationException("token不能为空");
        }
        //获得id
        Integer id=null;
        try {
            id = Integer.parseInt(JWTUtils.getAudience(token));
        } catch (NumberFormatException e) {
            throw new JWTVerificationException("token信息不正确");
        }
        //查询用户
        User user = userService.findById(id);
        if(user == null) {
            throw new JWTVerificationException("根据token信息没有查询到对应的用户");
        }
        //获得密钥对token进行校验
        JWTUtils.verifyToken(token,user.getUserPass());

        request.setAttribute("user",user);

        return true;
    }

}
